package Threads.GeekBang_test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;


//简易线程池，极客时间22
//生产者-消费者模式
public class test_22 {
    static class ThreadPool{
        static LinkedBlockingQueue<Runnable> workQueue;
        static List<WorkerThread> threads=new ArrayList<>();

        public ThreadPool(int poolSize,LinkedBlockingQueue<Runnable> workQueue){
            this.workQueue=workQueue;
            for (int i=0;i<poolSize;i++){
                WorkerThread workerThread=new WorkerThread();
                workerThread.start();
                threads.add(workerThread);
            }

        }
        static class WorkerThread extends Thread{
            @Override
            public void run() {
                while (true){
                    Runnable task = null;
                    try {
                        System.out.println("waiting to get the task");
                        task = workQueue.take();
                        System.out.println("complete the task");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    task.run();
                }
            }
        }

        public  void execute(Runnable task){
            workQueue.offer(task);
        }
    }

    //test
    public static void main(String[] args) {
        LinkedBlockingQueue<Runnable> workQueue=new LinkedBlockingQueue<Runnable>(2);
        ThreadPool pool=new ThreadPool(5,workQueue);
        pool.execute(()->{
            System.out.println("hello!");
        });
    }
}

